﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using fanfu.Common;
using fanfu.Business;
using fanfu.Model;
using System.Configuration;

public partial class Login : System.Web.UI.Page
{

    #region 注册客户端JS
    /// <summary>
    /// 客户端弹框
    /// </summary>
    /// <param name="msg">提示的内容</param>
    protected void Alert(string message)
    {
        ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "alert('" + message + "');", true);
    }

    /// <summary>
    /// 客户端运行JS
    /// </summary>
    /// <param name="js">待执行的JS</param>
    /// <param name="load">true页面加载后执行,false页面加载前执行</param>
    protected void RunJavascript(string javascript, bool load)
    {
        if (load == true)
            ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), javascript, true);
        else
            ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), javascript, true);
    }
    #endregion

    #region 区域或IP封杀
    /// <summary>
    /// 区域或IP封杀
    /// </summary>
    protected void Page_Init()
    {
        string _404html = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"><HTML><HEAD><TITLE>无法找到该页</TITLE><META HTTP-EQUIV=\"Content-Type\" Content=\"text/html; charset=GB2312\"><STYLE type=\"text/css\">   BODY { font: 9pt/12pt 宋体 }  H1 { font: 12pt/15pt 宋体 }  H2 { font: 9pt/12pt 宋体 }  A:link { color: red }  A:visited { color: maroon }</STYLE></HEAD><BODY><TABLE width=500 border=0 cellspacing=10><TR><TD> <h1>无法找到该页<font size='1' color='white'>lock</font></h1>您正在搜索的页面可能已经删除、更名或暂时不可用。<hr><p>请尝试以下操作：</p><ul><li>确保浏览器的地址栏中显示的网站地址的拼写和格式正确无误。</li><li>如果通过单击链接而到达了该网页，请与网站管理员联系，通知他们该链接的格式不正确。</li><li>单击<a href=\"javascript:history.back(1)\">后退</a>按钮尝试另一个链接。</li></ul><h2>HTTP 错误 404 - 文件或目录未找到。<br>Internet 信息服务 (IIS)</h2><hr><p>技术信息（为技术支持人员提供）</p><ul><li>转到 <a href=\"http://go.microsoft.com/fwlink/?linkid=8180\">Microsoft 产品支持服务</a>并搜索包括&ldquo;HTTP&rdquo;和&ldquo;404&rdquo;的标题。</li><li>打开&ldquo;IIS 帮助&rdquo;（可在 IIS 管理器 (inetmgr) 中访问），然后搜索标题为&ldquo;网站设置&rdquo;、&ldquo;常规管理任务&rdquo;和&ldquo;关于自定义错误消息&rdquo;的主题。</li></ul></TD></TR></TABLE></BODY></HTML>";
        string userIP = Request.UserHostAddress;
        IPLocation ipLocation = new QQWryLocator().Query(userIP);
        if (!string.IsNullOrEmpty(ipLocation.Country))
        {
            string sqlString = string.Format("SELECT COUNT(*) FROM BrowseLimit WHERE AreaorIP like '%{0}%' OR AreaorIP like '%{1}%'", userIP, ipLocation.Country);
            int result = int.Parse(SqlHelper.GetScalar(sqlString).ToString());
            if (result >= 1)
            {
                Response.Clear();
                Response.Write(_404html);
                Response.End();
                return;
            }
        }
    }
    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string isRememberPwd = CookieHelper.GetCookie("rememberPwd");
            if (isRememberPwd == "true")
            {
                this.chkRememberPwd.Checked = true;
                this.txtUserName.Value = CookieHelper.GetCookie("userName");
                this.txtUserPwd.Attributes.Add("value ", "尔等休得偷看密码");
                this.txtValidate.Focus();
            }
            else
            {
                this.txtUserName.Focus();
            }
        }
    }
    #endregion

    #region 用户登录
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string userName = this.txtUserName.Value.Trim();
        string userPwd = this.txtUserPwd.Value.Trim();
        string validate = txtValidate.Value.Trim().ToUpper();
        bool rememberPwd = this.chkRememberPwd.Checked;
        
        //获取IP信息
        string lastLoginIP = Request.UserHostAddress;
        IPLocation ipLocation = new QQWryLocator().Query(lastLoginIP);
        lastLoginIP = ipLocation.IP + ipLocation.Country + ipLocation.Local;

        //是否记住密码
        if (this.txtUserPwd.Value == "尔等休得偷看密码")
            userPwd = CookieHelper.GetCookie("userPwd");
        else
            userPwd = MD5.MD5ToHexString(userPwd);

        //验证码验证
        if (validate != Session["validateKey"].ToString())
        {
            RunJavascript("Appear('验证码错误，请重新输入！');", true);
            this.txtValidate.Focus();
            return;
        }

        #region 登录验证

        AdminUserModel adminUser = new AdminUserRule().UserLogin(userName, userPwd);
        if (adminUser.ID != 0)
        {
            //账号是否锁定
            if (adminUser.Flag == (byte)AdminUserFlag.locked)
            {
                RunJavascript("Appear('账号已锁定！');", true);
                this.txtUserName.Focus();
                return;
            }

            #region 创建和修改用户信息的Cookie

            //记住密码
            if (rememberPwd)
            {
                CookieHelper.SaveCookie("rememberPwd", "true", 14);
                CookieHelper.SaveCookie("userName", userName, 14);
                CookieHelper.SaveCookie("userPwd", userPwd, 14);
            }
            else
            {
                CookieHelper.ClearCookie("rememberPwd");
                CookieHelper.ClearCookie("userPwd");
                CookieHelper.SaveCookie("userName", userName, 0);
            }
            CookieHelper.SaveCookie("loginState", "true", 0);
            CookieHelper.SaveCookie("userAlias", adminUser.UserAlias, 0);
            #endregion

            #region 登录记录日志
            //登录记录日志
            string loginLog = "用户名:【" + userName;
            loginLog += "】 用户别名:【" + adminUser.UserAlias;
            loginLog += "】 登录IP:【" + lastLoginIP;
            loginLog += "】 操作系统:【" + Request.Browser.Platform;
            try { loginLog += "】 系统用户:【" + System.Net.Dns.GetHostEntry(Request.UserHostName).HostName; }catch (Exception ex) { }
            loginLog += "】 浏览器:【" + Request.Browser.Browser + Request.Browser.Version + "】";
            LogHelper.WriterLog(loginLog, LogHelper.LogType.LoginLog);
            #endregion 登录记录日志

            //更新登陆次数,时间,LoginIP,锁定账户
            new AdminUserRule().UpdateLoginMessage(lastLoginIP,userName);
            Response.Redirect("MainPage.aspx");
        }
        else
        {
            RunJavascript("Appear('用户名或密码错误！');", true);
            this.txtUserName.Focus();
        }
        #endregion
    }
    #endregion
}